import Taro, { useLoad, useRouter } from '@tarojs/taro'
import { useState } from 'react'
import { getSingleOrderInfoByID, payOrder } from '@/api/myOrder'
import { getUserInfoService } from '@/api/user'
import { AtMessage, AtModal } from 'taro-ui'
import { SET_USER } from '@/constants'
import { useDispatch, useSelector } from 'react-redux'
import { UserState } from '@/reducers/user'
import { OrderDetail } from './type'
import styles from './index.module.scss'

export default function Pay() {
  const dispatch = useDispatch()
  const user: UserState = useSelector((state: any) => state.user)
  const router = useRouter()
  const [orderId] = useState(router.params.id)
  const [orderInfo, setOrderInfo] = useState<OrderDetail>()
  const [showNewOrderModal, setShowNewOrderModal] = useState(false)
  const [payMethod, setPayMethod] = useState<string>('余额支付')
  const handlePayAmountMoney = async () => {
    try {
      const res = await payOrder({
        orderId,
        goodsId: orderInfo?.productId as number,
        payMethod: payMethod as string,
      })
      if (res.code == 0) {
        Taro.atMessage({
          message: '订单支付成功',
          type: 'success',
          duration: 1000,
        })
        setTimeout(() => {
          Taro.redirectTo({
            url: `/moduleA/pages/myOrder/index`,
          })
        }, 1000)
        getUserInfo()
      } else {
        Taro.showToast({
          title: res.msg,
          icon: 'error',
        })
      }
    } catch {
      console.log('订单支付过程中出现了错误')
    }
  }
  const handleConfirm = () => {
    setShowNewOrderModal(false)
    handlePayAmountMoney()
  }

  const getUserInfo = async () => {
    try {
      const res = await getUserInfoService()
      if (res.code === 0) {
        if (res.data.phone === null) {
          res.data.phone = '未绑定'
        }
        if (res.data.realName === null) {
          res.data.realName = '未绑定'
        }
        dispatch({
          type: SET_USER,
          payload: {
            avatar: res.data.avatar,
            nickname: res.data.nickName,
            amount: res.data.amount,
            phone: res.data.phone,
            realName: res.data.realName,
            sex: res.data.sex,
          },
        })
        console.log('打印个人信息请求信息：', res)
      }
    } catch (err) {
      console.log(err)
    }
  }

  useLoad(async () => {
    const { id } = router.params

    const fetchGetSingleOrderInfoByID = async () => {
      const { data } = await getSingleOrderInfoByID(id as string)
      console.log('获取到的订单详情', data)
      setOrderInfo(data.orderDetail)
    }
    fetchGetSingleOrderInfoByID()
  })

  return (
    <>
      <div className={styles.pay}>
        <div className={styles.topPart}>
          <div className={styles.orderBox}>
            <div className={styles.orderDetail}>
              {/* <div className={styles.goodPic}></div> */}
              <img
                className={styles.goodPic}
                src={orderInfo?.productCover}
                alt=''
              />
              <div className={styles.goodInfo}>
                <div className={styles.goodDesc}>{orderInfo?.productName}</div>
                <div className={styles.goodPrice}>¥ {orderInfo?.price}</div>
                <div className={styles.goodNum}>x{orderInfo?.count}</div>
              </div>
            </div>
          </div>
          <div
            className={styles.payBox}
            onClick={() => setPayMethod('余额支付')}
          >
            <div className={styles.payBoxAmount}>
              <img
                className={styles.moneyIcon}
                src={require('@/assets/pay/money.png')}
                alt=''
              />
              <div className={styles.save}>
                余额支付<span className={styles.money}>({user.amount})</span>
              </div>
            </div>
            {payMethod === '余额支付' ? (
              <img
                className={styles.wxIcon}
                src={require('@/assets/pay/Wx.png')}
                alt=''
              />
            ) : (
              <img
                className={styles.wxIcon}
                src={require('@/assets/pay/blank.png')}
                alt=''
              />
            )}
          </div>
          <div
            className={styles.payBox}
            onClick={() => setPayMethod('微信支付')}
          >
            <div className={styles.payBoxAmount}>
              <img
                className={styles.moneyIcon}
                src={require('@/assets/pay/Wxpic.png')}
                alt=''
              />
              <div className={styles.save}>
                微信支付<span className={styles.money}></span>
              </div>
            </div>
            {payMethod === '微信支付' ? (
              <img
                className={styles.wxIcon}
                src={require('@/assets/pay/Wx.png')}
                alt=''
              />
            ) : (
              <img
                className={styles.wxIcon}
                src={require('@/assets/pay/blank.png')}
                alt=''
              />
            )}
          </div>
        </div>
        <div className={styles.footerPart}>
          <div className={styles.payMoney}>应付款金额：¥{orderInfo?.price}</div>
          <div
            className={styles.payBtn}
            onClick={() => setShowNewOrderModal(true)}
          >
            立即支付
          </div>
        </div>
      </div>
      <AtMessage />
      <AtModal
        isOpened={showNewOrderModal}
        title='标题'
        cancelText='取消'
        confirmText='确认'
        onClose={() => setShowNewOrderModal(false)}
        onCancel={() => setShowNewOrderModal(false)}
        onConfirm={handleConfirm}
        content='只差一步即可获得此商品，确认付款吗？'
      />
      <AtMessage />
    </>
  )
}
